package com.jimmyhsu.ecnudaowei.coursetable.sync;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TextInputLayout;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.jimmyhsu.ecnudaowei.Bean.TaskActivity;
import com.jimmyhsu.ecnudaowei.Db.User;
import com.jimmyhsu.ecnudaowei.Db.UserDbHelper;
import com.jimmyhsu.ecnudaowei.MyApplication;
import com.jimmyhsu.ecnudaowei.R;
import com.jimmyhsu.ecnudaowei.Utils.EcnuUtils;
import com.jimmyhsu.ecnudaowei.Utils.PreferenceUtils;
import com.jimmyhsu.ecnudaowei.coursetable.CourseTableFragment;
import com.jimmyhsu.ecnudaowei.login.LoginActivity;
import com.jimmyhsu.ecnudaowei.person.MeActivity;
import com.jimmyhsu.ecnudaowei.verify.SchoolVerifyActivity;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * Created by jimmyhsu on 2017/3/14.
 */

public class CourseSyncFragment extends Fragment implements EcnuUtils.OnGetCourseListner {

    public static final String TAG = "CourseSyncFragment";
    public static final String ACTION_SYNC_SUCCESS = "com.jimmyhsu.ecnudaowei.broadcast.sync_success";

    private Unbinder mUnbinder;
    private EcnuUtils mEcnuUtils;

    @BindView(R.id.id_ct_sync_captcha)
    EditText mCaptchaCode;

    @BindView(R.id.id_ct_sync_captcha_img)
    ImageView mImgCaptcha;

    @BindView(R.id.id_ct_sync_idc)
    TextInputLayout mIdcView;

    @Nullable
    @BindView(R.id.id_ct_sync_idc_pwd)
    EditText mIdcPwd;

    private String mStuId;
    private String mPassword;
    private boolean isPasswordRemebered = true;

    private UserDbHelper mDbHelper = UserDbHelper.getInstance(getContext());


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.frag_course_sync, container, false);
        mUnbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        MyApplication.getInstance(getContext()).getId();
        if (TextUtils.isEmpty(mPassword=PreferenceUtils.getPreference(getContext(), LoginActivity.SP_NAME)
                .getString(SchoolVerifyActivity.SP_IDC_PASSWORD, ""))) {
            mIdcView.setVisibility(View.VISIBLE);
            isPasswordRemebered = false;
        } else {
            mIdcView.setVisibility(View.GONE);
        }
        initStuId();
        mEcnuUtils = new EcnuUtils();
        mEcnuUtils.prepare(mImgCaptcha);
    }

    private void initStuId() {
        String sql = "select " + User.COL_STU_ID + " from " + User.TB_NAME +
                " where _id=1";
        Cursor cursor = mDbHelper.getReadableDatabase().rawQuery(sql, null);
//        cursor.moveToFirst();
        if (cursor.moveToFirst()) {
            mStuId = cursor.getString(cursor.getColumnIndex(User.COL_STU_ID));
            cursor.close();
        }
        if (mStuId == null) {
            Toast.makeText(getContext(), "请先进行实名验证", Toast.LENGTH_SHORT).show();
            cursor.close();
            MeActivity.startActivity(getContext());
        }

    }

    @OnClick(R.id.id_ct_sync_go)
    void sync() {
        String captcha = mCaptchaCode.getText().toString();
        if (TextUtils.isEmpty(captcha) || captcha.length() != 4) {
            mCaptchaCode.setError("验证码长度错误");
            mCaptchaCode.requestFocus();
            return;
        }
        if (!isPasswordRemebered) {
            mPassword = mIdcPwd.getText().toString();
            if (TextUtils.isEmpty(mPassword)) {
                mIdcPwd.setError("密码必须填写");
                mIdcPwd.requestFocus();
                return;
            }
        }
        mEcnuUtils.getCourseTable(mStuId, mPassword, captcha, this);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mUnbinder.unbind();
    }

    @Override
    public void onCourseGet(boolean success, List<TaskActivity> courseTable) {
        if (success) {
            SQLiteDatabase db = mDbHelper.getWritableDatabase();
            db.execSQL("delete from " + TaskActivity.TB_COURSE);
            for (TaskActivity course : courseTable) {
                ContentValues values = new ContentValues();
                values.put(TaskActivity.COL_COURSE_ID, course.getCourseId());
                values.put(TaskActivity.COL_COURSE_NAME, course.getCourseName());
                values.put(TaskActivity.COL_LOCATION, course.getLocation());
                values.put(TaskActivity.COL_TEACHER, course.getTeacher());
                values.put(TaskActivity.COL_COURSE_WEEK, course.getCourseWeek());
                values.put(TaskActivity.COL_DURATION, course.getDuration());
                values.put(TaskActivity.COL_DAY, course.getDay());
                values.put(TaskActivity.COL_NUMBER, course.getNumber());
                values.put(TaskActivity.COL_ADD_BY_USER, 0);
                long id = db.insert(TaskActivity.TB_COURSE, null, values);
                if (id < 0) {
                    Toast.makeText(getContext(), "发生未知错误", Toast.LENGTH_SHORT).show();
                }
            }
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(40, TimeUnit.SECONDS)
                    .writeTimeout(40, TimeUnit.SECONDS)
                    .readTimeout(40, TimeUnit.SECONDS)
                    .build();
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(LoginActivity.BASE_URL)
                    .addConverterFactory(ScalarsConverterFactory.create())
                    .client(client)
                    .build();
            UploadCourses uploadCourses = retrofit.create(UploadCourses.class);
            Call<String> uploadCall = uploadCourses.upload(MyApplication.getInstance(getActivity()).getName(),
                    MyApplication.getInstance(getActivity()).getAndroidId(getActivity()),
                    new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().toJson(courseTable));
            uploadCall.enqueue(new Callback<String>() {
                @Override
                public void onResponse(Call<String> call, Response<String> response) {
                    goBack();
                }

                @Override
                public void onFailure(Call<String> call, Throwable t) {
                    Toast.makeText(getContext(),
                            "上传课程信息失败，不影响查看课程表，但会影响签到等功能，建议稍后重新同步", Toast.LENGTH_SHORT)
                            .show();
                    goBack();
                }
                private void goBack() {
                    PreferenceUtils.addToPreference(LoginActivity.SP_NAME, getContext(),
                            SchoolVerifyActivity.SP_IDC_PASSWORD, mPassword);
                    PreferenceUtils.addToPreference(CourseTableFragment.SP_COURSE, getContext(),
                            CourseTableFragment.SP_KEY_SYNCED, true);
                    Intent intent = new Intent();
                    intent.setAction(ACTION_SYNC_SUCCESS);
                    getContext().sendBroadcast(intent);
                }
            });
            db.close();

        } else {
            Snackbar.make(mImgCaptcha, "连接数据库失败", Snackbar.LENGTH_SHORT).show();
        }
    }
}
